import {myAjax} from './AjaxBox.js'
import {showBox} from './index.js'
import { ajax01 } from './AjaxBox.js'
import { displayLoinBox } from './index.js'


//实现注册功能
const loginBoxBtn01 = document.querySelector('.loginBoxBtn01')
// console.log( document.querySelector('#trae'))
// console.log( document.querySelector('.loginBoxHead span:nth-child(1)'))
const loginBoxFormSpans = document.querySelectorAll('.loginBoxForm span')

// console.log(loginBoxFormSpans)
//验证函数
function checkInfo(email,username,password) {
      //判断邮箱是否合法
    //根据正则表达式判断 ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
    if(!email.match(/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/)){
        loginBoxFormSpans[0].innerHTML = '请输入正确的邮箱'
        return
    } else {
        loginBoxFormSpans[0].innerHTML = ''
    }

    //判断用户名是否合法
    if(username.length < 2 || username.length > 16){
        loginBoxFormSpans[1].innerHTML = '用户名不能小于2位大于16位'
        return
    }else {
        loginBoxFormSpans[1].innerHTML = ''
    }
    //判断密码是否合法
    if(password.length < 6 || password.length > 16){
        loginBoxFormSpans[2].innerHTML = '密码不能小于6位大于16位'
        return
    }else {
        
        loginBoxFormSpans[2].innerHTML = ''
    }

    //判断是否勾选同意协议

    if(!document.querySelector('#trae').checked){    
        alert('请勾选同意协议')
        return
    }
    return true
}


loginBoxBtn01.addEventListener('click',function(){
    let email = document.querySelector('[data-name="email"]').value
    let username = document.querySelector('[data-name="userName"]').value
    let password = document.querySelector('[data-name="passWord"]').value

   if(checkInfo(email,username,password)) {
    myAjax({
        url:'http://43.136.111.27:8086/user/register',
        method:'post',
        data:{
            "email" : email,
            "username" : username,
            "password" : password
        }
        }).then(res=>{
            console.log(res)
            //注册成功后跳转到首页
            if(res.code === '200'){
                document.querySelector('.containerMain').style.display='flex'
                document.querySelector('.personalBox').style.display='none'
                document.querySelector('.personalDataBox').style.display='none'
                document.querySelector('.loginBox').style.zIndex='-1'
                document.querySelector('.popUpLogin').style.display='none'
                alert('注册成功 请登录')
                document.querySelector('[data-name="email"]').value = ''
                document.querySelector('[data-name="userName"]').value = ''
                document.querySelector('[data-name="passWord"]').value = ''

            }
            
        }).catch(err=>{
            console.log(err)
        })
   }

   
    
    })

//实现登录功能

const loginBoxBtn02 = document.querySelector('.loginBoxBtn02')


loginBoxBtn02.addEventListener('click',function(){
    let email = document.querySelector('[data-name="email"]').value
    let username = document.querySelector('[data-name="userName"]').value
    let password = document.querySelector('[data-name="passWord"]').value
    let email02 = localStorage.getItem('email') || ' '
    let username02 = localStorage.getItem('username') || ' '
    let password02 = localStorage.getItem('password') || ' '

   if((email === email02 && username === username02 && password === password02
        || email02 ===' '&& username02 ===' '&& password02 ===' ')
        &&checkInfo(email,username,password) ){
    myAjax({
        url:'http://43.136.111.27:8086/user/login',
        method:'post',
        params:{
            "email" : email,
            "password" : password
            }
        }).then(res=>{
            console.log(res)  
            const token = res.data        
            console.log(token)
            //把token保存到本地
            localStorage.setItem('token',token)
            //把邮箱、用户名和密码保存到本地
            localStorage.setItem('email',email)
            localStorage.setItem('username',username)
            localStorage.setItem('password',password)


            //登录成功后跳转到首页
            if(res.code === '200'){
                document.querySelector('.containerMain').style.display='flex'
                document.querySelector('.personalBox').style.display='none'
                document.querySelector('.personalDataBox').style.display='none'
                document.querySelector('.loginBox').style.zIndex='-1'
                document.querySelector('.containerBox').classList.remove('fixed')
                // loginBox.style.display='none'
                document.querySelector('.registrationAndLoginPart02').style.display='none'
                //yoyo弹窗消失
                document.querySelector('.popUpLogin').style.display='none'
                //登录成功后，登录框消失，登录成功后的样式出现
                document.querySelector('.registrationAndLoginPart02_').style.display='block'
                alert('登录成功')
                document.querySelector('[data-name="email"]').value = ''
                document.querySelector('[data-name="userName"]').value = ''
                document.querySelector('[data-name="passWord"]').value = ''
            }
             
        })
   } else {
        alert('请输入正确的邮箱、用户名和密码')
   }

 })





 //实现刷新后仍然保持登录状态，除非退出登录
 window.addEventListener('load',function(){
    let token = localStorage.getItem('token')
    let email = localStorage.getItem('email')
    let username = localStorage.getItem('username')
    let password = localStorage.getItem('password')
    if(token&&email&&username&&password){
        myAjax({
            url:'http://43.136.111.27:8086/user/login',
            method:'post',
            params:{
                "email" : email,
                "username" : username,
                "password" : password

                }
            }).then(res=>{
             
                if(res.code === '200'){
                    document.querySelector('.containerMain').style.display='flex'
                    document.querySelector('.personalBox').style.display='none'
                    document.querySelector('.personalDataBox').style.display='none'
                    document.querySelector('.loginBox').style.zIndex='-1'
                    document.querySelector('.containerBox').classList.remove('fixed')
                     // loginBox.style.display='none'
                     
                 

                document.querySelector('.registrationAndLoginPart02').style.display='none'
                //yoyo弹窗消失
                document.querySelector('.popUpLogin').style.display='none'
                //登录成功后，登录框消失，登录成功后的样式出现
                document.querySelector('.registrationAndLoginPart02_').style.display='block'
                }
            })
    }
 })
//7天后自动清除token，邮箱、用户名和密码，类似7天免登陆
window.addEventListener('load',function(){
    let token = localStorage.getItem('token')
    let email = localStorage.getItem('email')
    let username = localStorage.getItem('username')
    let password = localStorage.getItem('password')
    if(token&&email&&username&&password){
        setTimeout(function(){
            localStorage.removeItem('token')
            localStorage.removeItem('email')
            localStorage.removeItem('username')
            localStorage.removeItem('password')
        },1000*60*60*24*7)
    }
})






/* =====================================搜索功能设计================================================ */
const searchBtn = document.querySelector('[placeholder="搜索稀土掘金"]')
const searchImg = document.querySelector('.search-img')
// console.log(searchImg)
const historyBoxMainList = document.querySelector('.historyBoxMainList')
//获取清空搜索历史记录的按钮
const historyBoxHeadClear = document.querySelector('.historyBoxHead span:last-child')
// console.log(historyBoxHeadClear)

const searchHistoryList = []
//每次刷新页面时，把本地存储的搜索历史记录存入数组
//把包含searchHistory的key存入数组
for(let i=0;i<localStorage.length;i++){
    if(localStorage.key(i).includes('searchHistory')){
        searchHistoryList.push(localStorage.getItem(localStorage.key(i)))
        historyBoxMainList.innerHTML = searchHistoryList.map(item=>{
            return `<li>${item}</li>`
        }).join('')
    }
}


//点击清空搜索历史记录按钮，清空数组，清空本地存储
historyBoxHeadClear.addEventListener('click',function(){
    searchHistoryList.length = 0
    historyBoxMainList.innerHTML = ''
    
    //把本地存储的key为searchHistory的项全部删除
    for(let i=0;i<localStorage.length;i++){
        if(localStorage.key(i).includes('searchHistory')){
            localStorage.removeItem(localStorage.key(i))
        }
    }
})

function historyList(){
    const searchValue = searchBtn.value

//本地数据查重，如果有重复的，则不添加
//先获取本地存储的key，判断是否包含相同的value，如果包含，则不添加
    for(let i=0;i<localStorage.length;i++){
        if(localStorage.key(i).includes('searchHistory')){
            if(localStorage.getItem(localStorage.key(i)) === searchValue){
                
                return
            }
        }
    }
   if(searchValue && searchValue.trim() !== ''){
    searchHistoryList.push(searchValue)
    localStorage.setItem(`searchHistory${searchHistoryList.length}`,searchValue)
    historyBoxMainList.innerHTML = searchHistoryList.map(item=>{
        return `<li>${item}</li>`
    }).join('')


   } else{
        searchBtn.value = ''
   }
    
}

//如果输入正确的搜索内容，则跳转搜索结果页面
function toSearch (){
    const searchValue = searchBtn.value
    if(searchValue && searchValue.trim() !== ''){
        showBox('searchPageBox')

    }
}


//搜索请求，获取搜索结果，并渲染到页面
const searchArticle = document.querySelector('.searchPageHeaderNav li:nth-child(2)')
const searchUser = document.querySelector('.searchPageHeaderNav li:last-child')
// console.log(searchArticle)
// console.log(searchUser)
const mostHot = document.querySelector('.searchPageMainNav span:nth-child(2)')
const mostNew = document.querySelector('.searchPageMainNav span:last-child')
// console.log(mostHot)
// console.log(mostNew)
searchArticle.addEventListener('click',function(){
    searchNew()
    searchHot()
})
searchUser.addEventListener('click',function(){
    searchCreators()
})

mostHot.addEventListener('click',function(){
    searchHot()
})
mostNew.addEventListener('click',function(){
    searchNew()
})

function searchNew() {
    const searchValue = searchBtn.value
    const searchInfo = [] 

    ajax01({
        url:'http://43.136.111.27:8086/search/article/newest',
        method:'GET',
        authorization:localStorage.getItem('token'),
         params :`keyword=${searchValue}`
    }).then(res=>{
        console.log(res)
            res.data.forEach(item=>{
                searchInfo.push(item)
            })
    
            const searchPageMainContentBox = document.querySelector('.searchPageMainContentBox')
            searchPageMainContentBox.innerHTML = searchInfo.map(item=>{
                return `
                     <div class="searchPageMainContent">
                                    <div class="searchPageMainContentIntro">
                                        <div class="searchPageMainContentTime">${item.createTime}</div>
                                        <div class="searchPageMainContentTitle">${item.title}</div>
                                        <div class="searchPageMainContentText">
                                        ${item.summary}
                                        </div>
                                        <div class="searchPageMainContentFooter">
                                            <span>浏览:${item.viewCount}</span>
                                            <span>收藏:${item.collectCount}</span>
                                            <span>点赞:${item.likeCount}</span>
                                        </div>
                                    </div>
                                    <div class="searchPageMainContentImg">
                                        <img src="${item.coverUrl}" alt="图片"
                                            onerror="this.src='https://lf3-cdn-tos.bytescm.com/obj/static/xitu_juejin_web/img/default.640d9a7.png'"
                                        >
                                    </div>
                                </div>
                `
            }).join('')
    
    }).catch(err=>{
        console.log(err)
    })
}

function searchHot() {
    const searchValue = searchBtn.value
    const searchInfo = [] 

    ajax01({
        url:'http://43.136.111.27:8086/search/article/hottest',
        method:'GET',
        authorization:localStorage.getItem('token'),
         params :`keyword=${searchValue}`
    }).then(res=>{
        console.log(res)
            res.data.forEach(item=>{
                searchInfo.push(item)
            })
    
            const searchPageMainContentBox = document.querySelector('.searchPageMainContentBox')
            searchPageMainContentBox.innerHTML = searchInfo.map(item=>{
                return `
                     <div class="searchPageMainContent">
                                    <div class="searchPageMainContentIntro">
                                        <div class="searchPageMainContentTime">${item.createTime}</div>
                                        <div class="searchPageMainContentTitle">${item.title}</div>
                                        <div class="searchPageMainContentText">
                                        ${item.summary}
                                        </div>
                                        <div class="searchPageMainContentFooter">
                                            <span>浏览:${item.viewCount}</span>
                                            <span>收藏:${item.collectCount}</span>
                                            <span>点赞:${item.likeCount}</span>
                                        </div>
                                    </div>
                                    <div class="searchPageMainContentImg">
                                        <img src="${item.coverUrl}" alt="图片"
                                            onerror="this.src='https://lf3-cdn-tos.bytescm.com/obj/static/xitu_juejin_web/img/default.640d9a7.png'"
                                        >
                                    </div>
                                </div>
                `
            }).join('')
    
    }).catch(err=>{
        console.log(err)
    })
}

function searchCreators () {
    const searchValue = searchBtn.value
    const searchInfo = [] 

    ajax01({
        url:'http://43.136.111.27:8086/search/article/creators',
        method:'GET',
        authorization:localStorage.getItem('token'),
         params :`keyword=${searchValue}`
    }).then(res=>{
        console.log(res)
            res.data.forEach(item=>{
                searchInfo.push(item)
            })
    
            const searchPageMainContentBox = document.querySelector('.searchPageMainContentBox')
            searchPageMainContentBox.innerHTML = searchInfo.map(item=>{
                return `
                   <div class="searchPageMainContentUser">
                                    <div class="searchPageMainContentUserImg">
                                        <img src="${item.avatar}" alt="图片"
                                        onerror="this.src='./images/用户头像.svg'"
                                        >
                                    </div>
                                    <div class="searchPageMainContentUserInfo">
                                       ${item.username}
                                    </div>
                                    <div class="searchPageMainContentUserFollow">关注</div>
                                </div>
                `
            }).join('')
    
    }).catch(err=>{
        console.log(err)
    })
}







//把每次搜索的内容保存到本地
searchImg.addEventListener('click',function(){
    //没有登录无法搜索，点击搜索按钮
    if(!localStorage.getItem('token')){
       alert('请先登录')
       return
    } else {
        historyList()
        toSearch()
    }
    // historyList()
    // toSearch()
    
})


//点击搜索框，显示搜索历史记录
searchBtn.addEventListener('click',function(){
   if(searchHistoryList.length){
    document.querySelector('.historyBox').style.display='block'
   }
})
document.addEventListener('click',function(e){
    if(e.target !== searchBtn){
       document.querySelector('.historyBox').style.display='none'
    }
})

//点击搜索历史记录，搜索框自动填充搜索历史记录,并自动搜索,并显示搜索内容
historyBoxMainList.addEventListener('click',function(e){
    if(e.target.tagName.toLowerCase() === 'li'){
        searchImg.click()
        searchBtn.value = e.target.innerHTML
    }
})


/* ================================================== 详细文章设计=============================================== */
const articleReadPageMiddleText = document.querySelector('.articleReadPageMiddleText')
const articleReadPageMiddleHeadH1 = document.querySelector('.articleReadPageMiddleHead h1')
const articleReadPageMiddleHeadSpan = document.querySelector('.articleReadPageMiddleHead span')
const articleReadPageListContent = document.querySelector('.articleReadPageListContent')
myAjax({
    url : 'http://43.136.111.27:8086/article/detail/1',
    data : {
        authorization : localStorage.getItem('token')
    }
}).then(res=>{
    // console.log(res.data)
    articleReadPageMiddleHeadH1.innerHTML = res.data.title
    articleReadPageMiddleHeadSpan.innerHTML = res.data.createTime
    articleReadPageMiddleText.innerHTML = res.data.content
    
    //把h1,h2,h3标签的id值赋值给articleReadPageListContent的a标签的href属性
    document.querySelectorAll('.articleReadPageMiddleText h1').forEach((item)=>{
        
        document.querySelector('.articleReadPageListContent').innerHTML += `
        <div data-title="h1">
            <a href="#${item.id}">${item.innerHTML}</a>
        </div>
        `
    })
    document.querySelectorAll('.articleReadPageMiddleText h2').forEach((item,index)=>{
        document.querySelector('.articleReadPageListContent [data-title="h1"]').innerHTML += `
        <div data-title="h2-${index}" data-id="h2">
         <a href="#${item.id}" data-name="h2">${item.innerHTML}</a>
        <div>
         `
    })
   
    document.querySelectorAll('.articleReadPageMiddleText h3').forEach((item)=>{
        document.querySelector('.articleReadPageListContent [data-title="h2-1"]').innerHTML += `
        <div data-title="h3">
         <a href="#${item.id}" data-name="h3">${item.innerHTML}</a>
        <div>
        `

    //点击标签，显示高亮
    document.querySelectorAll('.articleReadPageListContent a').forEach((item)=>{
        item.addEventListener('click',function(){
            document.querySelectorAll('.articleReadPageListContent a').forEach((item)=>{
                item.style.color = '#000'
            })
            this.style.color = '#1e80ff'
        })
    })


 })

 //文章滚动到那个标题，对应的导航栏标题高亮
const articleReadPageMiddleTextH1 = document.querySelector('.articleReadPageMiddleText h1')
const articleReadPageListContentH1 = document.querySelector('.articleReadPageListContent [data-title="h1"] a:first-child')
const articleReadPageMiddleTextH2 = document.querySelectorAll('.articleReadPageMiddleText h2')
const articleReadPageListContentH2 = document.querySelectorAll('.articleReadPageListContent [data-id="h2"] [data-name="h2"]')
// console.log(articleReadPageMiddleTextH2)
const articleReadPageMiddleTextH3 = document.querySelectorAll('.articleReadPageMiddleText  h3')
const articleReadPageListContentH3 = document.querySelectorAll('.articleReadPageListContent [data-title="h3"] [data-name="h3"]')
console.log(articleReadPageListContentH3)
console.log(articleReadPageMiddleTextH3)




window.addEventListener('scroll',function(){
    const windowTop = document.documentElement.scrollTop
   if(windowTop >= articleReadPageMiddleTextH1.offsetTop && windowTop < articleReadPageMiddleTextH2[0].offsetTop){
    articleReadPageListContentH1.style.color = '#1e80ff'
   } else {
    articleReadPageListContentH1.style.color = '#000'
   }
})

window.addEventListener('scroll',function(){
    const windowTop = document.documentElement.scrollTop
 for(let i = 0; i < articleReadPageMiddleTextH2.length-1; i++){
    if(windowTop >= articleReadPageMiddleTextH2[i].offsetTop && windowTop < articleReadPageMiddleTextH2[i+1].offsetTop){
        articleReadPageListContentH2[i].style.color = '#1e80ff'
     } else {
        articleReadPageListContentH2[i].style.color = '#000'
     }
    
 }
       if(windowTop >= articleReadPageMiddleTextH2[4].offsetTop){
        articleReadPageListContentH2[4].style.color = '#1e80ff'
       } else {
        articleReadPageListContentH2[4].style.color = '#000'
       }
   

})
window.addEventListener('scroll',function(){
    const windowTop = document.documentElement.scrollTop
 for(let i = 0; i < articleReadPageMiddleTextH3.length - 1 ; i++){
    if(windowTop >= articleReadPageMiddleTextH3[i].offsetTop && windowTop < articleReadPageMiddleTextH3[i+1].offsetTop){
        articleReadPageListContentH3[i].style.color = '#1e80ff'
     } else {
        articleReadPageListContentH3[i].style.color = '#000'
     }
    }
    if(windowTop >= articleReadPageMiddleTextH3[2].offsetTop && windowTop < articleReadPageMiddleTextH3[2].offsetTop+200){
        articleReadPageListContentH3[2].style.color = '#1e80ff'
    } else {
        articleReadPageListContentH3[2].style.color = '#000'
    }
})

    //滚动使导航栏隐藏
    const containerHead = document.querySelector('.container-head')
    window.addEventListener('scroll',function(){
        if(window.scrollY > 2000){
            containerHead.style.display = 'none'
        } else {
            containerHead.style.display = 'flex'
        }
    })

    })

/* -----------------------------沉浸阅读---------------------------- */
const articleReadPageLeft = document.querySelectorAll('.articleReadPageLeft div')
const readingBtn = document.querySelector('.articleReadPageLeft div:nth-child(6)')
// console.log(readingBtn)
readingBtn.addEventListener('click',function(){
    readingBtn.classList.toggle('finish')
    const token = localStorage.getItem('token')
    if(!token){
        displayLoinBox()
        return
    }

   if(readingBtn.classList.contains('reading')){
    readingBtn.classList.remove('reading')
    alert('已退出沉浸阅读模式')
    for(let i = 0; i < articleReadPageLeft.length - 1; i++){
        articleReadPageLeft[i].style.display = 'flex'
    }
   } else {
    readingBtn.classList.add('reading')
    alert('已进入沉浸阅读模式')
    for(let i = 0; i < articleReadPageLeft.length - 1; i++){
        articleReadPageLeft[i].style.display = 'none'
    }
   }
})



/* ----------------------评论功能------------------------------- */
function isComment() {
    const token = localStorage.getItem('token')
    if(!token){
        document.querySelector('.articleReadPageMiddleCommentInput').style.display = 'none'
        document.querySelector('.noloinBox').style.display = 'flex'
    } else {
        document.querySelector('.articleReadPageMiddleCommentInput').style.display = 'flex'
        document.querySelector('.noloinBox').style.display = 'none'
    }

    //没有登录不能使用功能
    for(let i = 0; i < articleReadPageLeft.length - 1; i++){
        articleReadPageLeft[i].addEventListener('click',function(){
            if(!token){
                displayLoinBox()
                return
            }
        })
    }

}

isComment()
const noloinBox = document.querySelector('.noloinBox')
noloinBox.addEventListener('click',function(){

    displayLoinBox()
})

function comment(commentInput) {
    ajax01({
        url : 'http://43.136.111.27:8086/article/comment/add',
        method : 'POST',
        data : {
            
                "articleId": 1,
                "content": `${commentInput}`,
                "imageUrl": "https://loremflickr.com/400/400?lock=2443527260066532",
     
            
        },
        
        authorization : localStorage.getItem('token')
    
    }).then(res=>{
        console.log(res)
        localStorage.setItem('commentId',res.data.commentId)
    }).catch(err=>{
        console.log(err)
    })
}


//获取文章评论列表
function getCommentList() {
    ajax01({
        url : 'http://43.136.111.27:8086/article/comment/list/1',
        method : 'GET',
        data : {
            articleId : 1
        },
        authorization : localStorage.getItem('token')
    
 }).then(res=>{
        // console.log(res.data)
        const commentList =[]
       res.data.forEach(item=>{
            commentList.unshift(item)
       })
        // console.log(commentList)
        const articleReadPageMiddleCommentDisplay = document.querySelector('.articleReadPageMiddleCommentDisplay')
        articleReadPageMiddleCommentDisplay.innerHTML =commentList.map(item=>{
            return`
             <div class="userCommentBox">
                                        <div class="userCommentImg">
                                            <img src="${item.imageUrl}" alt="用户头像"
                                            onerror="this.src='https://loremflickr.com/400/400?lock=2443527260066532'"
                                            >
                                        </div>
                                        <div class="userCommentInfo">
                                            <div class="userCommentName">${item.commentUser}</div>
                                            <div class="userCommentContent" data="${item.commentId}">${item.content}</div>
                                            <div class="userCommentFooter">
                                                <span>评论</span>
                                                <span>删除</span>
                                            </div>
                                        </div>
                                    </div>
            `
        }).join('')
        
        
        

 })
 .catch(err=>{
        console.log(err)
 })
}
getCommentList()

/* -----------------------------输入框文字检测---------------------------------- */
const commentInput = document.querySelector('.commentBox input')
const count = document.querySelector('.commentBoxButton div:first-child')
const commentBtn = document.querySelector('.commentBoxButton div:last-child')
commentInput.addEventListener('input',function(){
    //空格和符号不算字数
    const text = commentInput.value.replace(/[\s,.!?;:。！？；，、‘’“”'‘’]/g,'')
    
    count.innerHTML = `${text.length}/100`
    
})

/* ------------------发布评论----------------------------- */
commentBtn.addEventListener('click',function(){
    if(commentInput.value.length === 0 || commentInput.value.trim() === ''){
        alert('评论不能为空')
        return
    }
    comment(commentInput.value)
    commentInput.value = ''
    count.innerHTML = `0/100`
    getCommentList()
})
 
/* -----------------------------自己发布的评论可以删除---------------------- */
// const deleteComment = document.querySelector('.userCommentFooter span:last-child')
// // console.log(deleteComment)

// deleteComment.addEventListener('click',function(){
//     deleteCommentF()
// })
//  function deleteCommentF() {
//     const commentId = localStorage.getItem('commentId')
//      ajax01({
//          url : `http://43.136.111.27:8086//article/comment/delete/${commentId}`,
//          method : 'POST',
//          authorization : "eyJhbGciOiJIUzI1NiJ9.eyJpc0RlbGV0ZWQiOjAsInVzZXJJZCI6OTIsImlhdCI6MTc0NjI2Mjk4MywiZXhwIjoxNzQ2NDM1NzgzfQ.rQUp05cFCP4uWHBb9_L0MV_moXBWQlCBYfGAxaQ4fFM"
//      }).then(res=>{
//          console.log(res)
//          getCommentList()
//      }).catch(err=>{
//          console.log(err)
        
//  })
// }

/* ------------------------------------------点赞与取消点赞文章----------------------------------- */
const likeArticle = document.querySelector('.articleReadPageLeft div:first-child')
const collectArticle = document.querySelector('.articleReadPageLeft div:nth-child(3)')
// console.log(likeArticle)
// console.log(collectArticle)
likeArticle.addEventListener('click',function(){

   
   if (likeArticle.classList.contains('finish')){
        likeArticleF()
   } else {
        unLikeArticleF()
   }

   if(localStorage.getItem('token')){
    likeArticle.classList.toggle('finish')
   }
})
collectArticle.addEventListener('click',function(){
 
       
   if (collectArticle.classList.contains('finish')){
        collectArticleF()
   } else {
        unCollectArticleF()
   }
   if(localStorage.getItem('token')){
    collectArticle.classList.toggle('finish')

   }
})

function likeArticleF(num) {
    num=1
    ajax01({
        url : `http://43.136.111.27:8086/article/like/${num}`,
        method : 'POST',     
        authorization : localStorage.getItem('token')
}).then(res=>{
    console.log(res)

}).catch(err=>{
    console.log(err)
})
}
function unLikeArticleF(num) {
    num=1
    ajax01({
        url : `http://43.136.111.27:8086/article/unlike/${num}`,
        method : 'POST',
       
        authorization : localStorage.getItem('token')
}).then(res=>{
    console.log(res)

}).catch(err=>{
    console.log(err)
})
}

/* ------------------------------------------收藏与取消收藏文章----------------------------------- */
function collectArticleF(num) {
    num=1
    ajax01({
        url : `http://43.136.111.27:8086/article/collect/${num}`,
        method : 'POST',
        
        authorization : localStorage.getItem('token')
}).then(res=>{
    console.log(res)

}).catch(err=>{
    console.log(err)
})
}

function unCollectArticleF(num) {
    num=1
    ajax01({
        url : `http://43.136.111.27:8086/article/uncollect/${num}`,
        method : 'POST',
       
        authorization : localStorage.getItem('token')
}).then(res=>{
    console.log(res)

}).catch(err=>{
    console.log(err)
})
}


/* ---------------------个人信息渲染-------------------------------- */
//头像渲染
document.querySelector('#changeImgLabel').addEventListener('click',function(){
    changeImg()
})
function changeImg() {
    document.querySelector('#changeImg').addEventListener('change',function(e){
        const file = e.target.files[0];
        if (!file) {
            return;
        }
        if(!file.type.match('image.*')){
            alert('请选择图片文件');
            return;
        }
    //     const reader = new FileReader();
    //     reader.onload = function(e) {
    //         const img = document.getElementById('previewImage');
    //         img.src = e.target.result;
    //         img.style.objectFit = 'cover';
    //          //向后端发送图片地址，并更新头像
    //        upLoadImg(file)
    //     }
    console.log(file)
    
    upLoadImg(file)
       
    
        // reader.readAsDataURL(file)
    })
}

function upLoadImg(file) {
    // const fd = new FormData()
    // fd.append('avatar','.\images\阅读.svg')
    ajax01({
        url : 'http://43.136.111.27:8086/user/refresh/info',
        method : 'POST',
        data : {
            avatar : './images/阅读.svg'
        },
        authorization : localStorage.getItem('token')

    }).then(res=>{
        console.log(res)
        getImg()
    }).catch(err=>{
        console.log(err)
    })
    
}

function getImg() {
    ajax01({
        url : 'http://43.136.111.27:8086/user/get/userinfo',
        method : 'GET',
        authorization : localStorage.getItem('token')

    }).then(res=>{
        console.log(res)

        //把获取到的头像地址渲染到页面上
        document.querySelector('#previewImage').src = res.data.avatar

    })
}








const personalFormContentId = document.querySelectorAll('.personalFormContent [data-id]')
const keepButton = document.querySelector('.keepButton')
// console.log(personalFormContentId[0].dataset.id)
//获取输入的个人信息，上传到后端
function getPersonalInfo() {
    const personalInfo = {}
    personalFormContentId.forEach(item=>{
        personalInfo[item.dataset.id] = item.value
    })
//    console.log(personalInfo)
    ajax01({
        url : 'http://43.136.111.27:8086/user/refresh/info',
        method : 'POST',
        data : personalInfo,
        authorization : localStorage.getItem('token')
    }).then(res=>{
        console.log(res)
    })
   
}
keepButton.addEventListener('click',function(){
    getPersonalInfo()
    alert('保存成功')
})

//获取个人信息，渲染到页面
function getPersonalInfoF() {
    ajax01({
        url : 'http://43.136.111.27:8086/user/get/userinfo',
        method : 'GET',
        authorization : localStorage.getItem('token')
    }).then(res=>{
        console.log(res)
        // console.log(res.data.avatar)
        
        personalFormContentId.forEach(item=>{
            item.value = res.data[item.dataset.id]
        })
        getImg()
       
    })
        
}
getPersonalInfoF()

/* ---------------------------发布文章------------------------------ */
const creativeBtn = document.querySelector('.creative-box')
creativeBtn.addEventListener('click',function(){
    const token = localStorage.getItem('token')
    if(!token){
        alert('请先登录')
        displayLoinBox()
        return
    }
    showBox('publishArticleBox')
})

// 实现发布文章
const publishBtn = document.querySelector('.publishBtn')
publishBtn.addEventListener('click',function(){
    const publishTitle = document.querySelector('.publishTitle').value
    const publishContent = document.querySelector('.publishContent').value
    const publishSummary = document.querySelector('.publishSummary').value
    const publishTag = document.querySelector('.publishTag').value
    const publishClassify = document.querySelector('.publishClassify').value
    if (!publishTitle || !publishContent || !publishSummary || !publishTag || !publishClassify){
        alert('请填写完整信息')
        return
    }

    ajax01({
        url : 'http://43.136.111.27:8086/article/publish',
        method : 'POST',
        data : {
            title : publishTitle,
            content : publishContent,
            summary : publishSummary,
            labelId :publishClassify,
            tags : publishTag
        },
        authorization :localStorage.getItem('token')
    }).then(res=>{
        console.log(res)
        alert('发布成功')

        //数据清空
        document.querySelector('.publishTitle').value = ''
        document.querySelector('.publishContent').value = ''
        document.querySelector('.publishSummary').value = ''
        document.querySelector('.publishTag').value = ''
        document.querySelector('.publishClassify').value = ''

    }).catch(err=>{
        console.log(err)
    })
})